<template>
 <div id="editorDiv" >
  <!--对话框-->
  <div style="display: none">
   <Remind :note="this.note"
           ref="Remind"/>
  </div>
  <div v-if="note.nn_id" id="noteTopDiv">
      <!--顶部操作区域-->
      <div style="margin: 8px;">
          <!--任务复选框-->
          <a-checkbox v-if="note.nn_type==2" :checked="note.nn_is_finish==1?true:false" @change="saveByFinish"></a-checkbox>
          <!--提醒区域    7天前，2019年12月5日    -->
          <span style="margin: 0 10px;" @click="showRemind">{{dateTip}}</span>
          <a-icon v-if="note.nn_repeat==1" type="sync"/><!--是否为循环提醒类型-->
          <span style="margin-left: 10px;">
              <a-select v-model="note.nn_urgency" placeholder="请选择类型" @change="rightUrgency">
                <a-select-option :value="1" >重急</a-select-option>
                <a-select-option :value="2">轻急</a-select-option>
                <a-select-option :value="3">重缓</a-select-option>
                <a-select-option :value="4">轻缓</a-select-option>
              </a-select>
            </span>

          <div style="float: right;">
              <a style="padding: 5px" v-if="note.nn_type==1" type="link" size="small" @click="()=>{this.note.nn_type=2;this.save();}">转任务</a>
              <a v-if="note.nn_type==2" type="link" size="small" @click="()=>{this.note.nn_type=1;this.save();}">转笔记</a>

             <!-- <a-button v-show="note.nn_text_type==2" type="link" size="small" @click="toHTML">转html</a-button>
              <a-button v-show="note.nn_text_type==1" type="link" size="small" @click="toMD">转md</a-button>-->

              <a style="padding: 5px" type="link" size="small" @click="annexRefresh">附件</a>
              <Annex :annex_uuid="this.note.nn_id"
                     :doType="this.doType"
                     @insertValue="insertValue"
                     ref="Annex"
                     style="display:inline;padding: 5px"/>


              <a style="padding: 5px" v-if="doType=='show'" type="link" size="small" @click="editBtn">编辑</a>
              <a style="padding: 5px" v-else type="link" size="small" @click="saveBtn">保存</a>
              <a-popconfirm
                      title="是否删除该笔记?"
                      ok-text="确定"
                      cancel-text="取消"
                      @confirm="deleteNote"
              >
                  <a style="padding: 5px" type="link" size="small" href="#">删除</a>
              </a-popconfirm>
          </div>
      </div>
      <!--标题-->
      <div style="margin: 20px;">
          <a-input v-model="note.nn_title" @change="saveByTitle" placeholder="请输入云记标题"/>
      </div>
      <!--标签区域-->
      <div style="margin: 20px; ">
          <template v-for="(tag, index) in rightTags">
              <a-tag :key="tag.nlId" @close="() => deleteLable(tag)" :closable="true">
                  {{tag.nlName}}
              </a-tag>
          </template>
          <a-icon type="plus"  @click="showTag"  />
          <LableList :note="this.note"
                     :defaultValue="this.rightTags"
                     :defaultValueKey="'nlId'"
                     @change="saveLableNote"
                     ref="LableList"/>
      </div>
  </div>
   <!--编辑区域-->
   <div v-if="note.nn_id" id="noteMainDiv">
           <div id="noteEditdiv">
               <UEditor v-show="note.nn_text_type==1"
                        id="uEditor"
                        :table-id="note.nn_id"
                        :content="note.nn_content"
                        :doType="doType"
                        :nnTextType="note.nn_text_type"
                        @change="UEditorBlurSave"
                        ref="myUEditor" />
               <EditorMD  v-show="note.nn_text_type==2"
                          id="editorMD"
                          :table-id="note.nn_id"
                          :content="note.nn_content"
                          :doType="doType"
                          :nnTextType="note.nn_text_type"
                          :content_html="note.nn_content_html"
                          @change="autoSave"
                          ref="myEditorMd"/>
           </div>
       </div>
  <!--空显示-->
  <a-empty v-else style="margin-top: 200px;"/>
 </div>
</template>

<script>
 import EditorMD from "../../components/editor/EditorMD";
 import UEditor from "../../components/editor/UEditor";
 import Remind from "../../components/remind/Remind";
 import Annex from "../../components/annex/Annex";
 import LableList from "@/components/LableList";
 import {getAction , postAction,deleteAction} from '@/api/dl'
 import Turndown from "turndown";
 import Vue from 'vue'
 export default {
  name: "editor",
  components: {
   EditorMD,
   UEditor,
   Remind,
   Annex,
   LableList
  },
 props: {
     /*note:{//当前编辑的云记
         type: Object,
         default: ''
     },*/
 },
  data() {
   return {
    note:{},//当前编辑的云记
    dateTip: "时间提醒",
    //编辑和查看  editor  /  show
    doType: 'show',
    //选中的标签
    tagSelectIds: [],
    //标签集合
    tagList: [],
    //标签
    rightTags: [],
   }
  },
  created() {
  },
  methods: {
      setNote(o){
        this.note=o;
      },
      showRemind(){
          this.$refs.Remind.showRemind();
      },
      sessionStorage(){
          return this.webUrl;
      },
      //笔记操作开始
      /**
       * 设置任务完成或未完成
       * @param e
       */
      saveByFinish(e) {
          this.note.nn_is_finish=e.target.checked?1:0;
          this.save();
      },
      saveByTitle() {
          // console.log("saveByTitle");
          this.save();
      },
      /**
       * 保持标签与云记关系
       */
      saveLableNote(ids){
          postAction(`note/lable-note/save/${this.note.nn_id}`,{
              list:ids.join(",")
              }).then(res => {
              if (res.is) {
                  this.queryLable(this.note.nn_id);
                  this.$message.success('保存成功！');
              } else {
                  this.$message.warning("保存失败");
              }
          })
      },
      //确定删除笔记
      confirm(e) {
          this.deleteNote();
      },
      //删除笔记
      deleteNote() {
          deleteAction(`note/delete/${this.note.nn_id}`).then(res => {
              this.$message.success('删除完成！');
              this.refresh();
          })
      },
      /**
       * 删除标签与云记关系
       */
      deleteLable(lable){
          let nl_ids=lable.nlId;
          postAction('note/lable-note/deleteNoteLable',{
              nl_ids:nl_ids,
              nn_id:this.note.nn_id
          }).then(res=>{
              this.queryLable(this.note.nn_id);
          });
      },
      //插入附件
      insertValue(annex,type) {
          if(this.note.nn_text_type==1){//ueditor
              this.$refs.myUEditor.insertValue(annex,type);
          }else{//md
              this.$refs.myEditorMd.insertValue(annex,type);
          }
      },
      //查询笔记关联标签
      queryLable(noteId) {
          getAction(`note/lable-note/get/${noteId}`).then(res => {
              if (res.result.list != undefined && res.result.list.length > 0) {
                  this.rightTags = res.result.list;
              } else {
                  this.rightTags = [];
              }
              this.tagSelectIds = res.result.ids;
          });
      },
      findNoteByCode(nn_code) {
          getAction(`note/queryNoteByCode/${nn_code}`).then(res => {
              let that = this;
              if (res.is) {
                  this.dateTip=this.showDate(res.data.nn_start_time)?res.data.nn_start_time:"设置提醒时间";;  //res.data.nn_start_time?res.data.nn_start_time:"设置提醒时间";
                  this.convertRootWebUrl(res.data,1);
                  this.note = res.data;
                  this.note.nn_content_html = res.data.nn_content_html;
                  this.doType = 'show';
                  this.queryLable(this.note.nn_id);//加载标签关系
                  this.$emit('findNote',this.note);//同步到父组件
              } else {
                  this.$message.error(`笔记打开失败${res.message}！`);
              }
          })
      },
      //保存操作
      save() {
          //根目录处理
          this.convertRootWebUrl(this.note,2);
          postAction("note/saveOrUpdate", this.note).then(res => {
              if (res.is) {
                  this.convertRootWebUrl(res.data,1);
                  this.note = res.data;
                  this.$emit("updateListNote",this.note);
              } else {
                  this.$message.error(`${res.message}！`);
              }
          }).catch(error => {
              this.$message.error(`保存失败！`);
          })
      },
      //切换为保存
      saveBtn() {
          this.doType = 'show';
          if(this.note.nn_text_type==1){//ueditor
              this.note.nn_content=this.$refs.myUEditor.getUEContent();
          }
          this.save();
      },
      //切换为编辑
      editBtn() {
          this.doType = 'editor';
      },
      //当编辑器内容改变时候，会触发该事件，并返回一个html和markdown文本
      autoSave(html, text) {
          this.note.nn_content_html = html;
          this.note.nn_content = text;
      },
      //ueditor失去焦点，回响触发保存
      UEditorBlurSave(content) {
          this.note.nn_content = content;
          this.save();
      },
      toHTML() {
          this.note.nn_text_type=1;
          this.save();
      },
      toMD() {
          let markdown='';
          if(this.content){
              var turndownService = new Turndown()
              markdown = turndownService.turndown(this.content)
          }
          this.content=markdown;
          this.note.nn_text_type=2;
          this.save();
      },
      //笔记操作结束


      //附件操作
      annexRefresh(){
          // console.log("annexRefresh");
          this.$refs.Annex.load();
      },
      /**
       * 转换web根目录
       * @param type  1是："###path###"到正常显示路径   2是：显示路径到"###path###"
       */
      convertRootWebUrl(note,type){
          // if(type==1){
          //   if(note.nn_content)note.nn_content=note.nn_content.replaceAll("###path###",Vue.prototype.webUrl);
          //   if(note.nn_content_html)note.nn_content_html=note.nn_content_html.replaceAll("###path###",Vue.prototype.webUrl);
          // }
          //
          // if(type==2){
          //     if(note.nn_content)note.nn_content=note.nn_content.replaceAll(Vue.prototype.webUrl,"###path###");
          //     if(note.nn_content_html)note.nn_content_html=note.nn_content_html.replaceAll(Vue.prototype.webUrl,"###path###");
          // }
      },
      showDate(dateStr){
          if(!dateStr){
              return "";
          }

          var publishTime = this.getDateTimeStamp(dateStr) / 1000,
              d_seconds,
              d_minutes,
              d_hours,
              d_days,
              timeNow = parseInt(new Date().getTime() / 1000),
              d,
              date = new Date(publishTime * 1000),
              Y = date.getFullYear(),
              M = date.getMonth() + 1,
              D = date.getDate(),
              H = date.getHours(),
              m = date.getMinutes(),
              s = date.getSeconds();

          // console.log(publishTime);

          //小于10的在前面补0
          if (M < 10) {
              M = '0' + M;
          }
          if (D < 10) {
              D = '0' + D;
          }
          if (H < 10) {
              H = '0' + H;
          }
          if (m < 10) {
              m = '0' + m;
          }
          if (s < 10) {
              s = '0' + s;
          }

          d = timeNow - publishTime;
          d_days = parseInt(d / 86400);
          d_hours = parseInt(d / 3600);
          d_minutes = parseInt(d / 60);
          d_seconds = parseInt(d);

          if (d_days > 0 && d_days < 3) {
              return d_days + '天前';
          } else if (d_days <= 0 && d_hours > 0) {
              return d_hours + '小时前';
          } else if (d_hours <= 0 && d_minutes > 0) {
              return d_minutes + '分钟前';
          } else if (d_seconds < 60) {
              if (d_seconds <= 0) {
                  return '刚刚';
              } else {
                  return d_seconds + '秒前';
              }
          } else if (d_days >= 3 && d_days < 30) {
              return M + '-' + D + ' ' + H + ':' + m;
          } else if (d_days >= 30) {
              return Y + '-' + M + '-' + D + ' ' + H + ':' + m;
          }
      },
      getDateTimeStamp(dateStr) {
         // 如果时间格式为2020/07/09 21:43:19.000  需要去掉.000 不然ios和firefox会有问题
         return Date.parse(dateStr.replace(/-/gi, "/"));
      },

      refresh() {
          this.$emit('queryPageRefresh');//刷新云记列表
      },
      //标签树左侧的checkbox
      onCheck(checkedKeys, info) {
          console.log('onCheck', checkedKeys, info);
          this.tagSelectIds = checkedKeys.checked;
      },
      //递归添加插槽
      addSlot(list) {
          console.log("list=> ", list);
          for (let i = 0; i < list.length; i++) {
              list[i].scopedSlots = {title: "custom"};
              if (list[i].childList.length > 0) {
                  this.addSlot(list[i].childList);
              }
          }
      },
      //树节点展开
      onExpand(keys) {
          console.log('onExpand', keys)
      },
      //树节点事件
      onSelect(checkedKeys, info) {
          console.log('onSelect', checkedKeys, info)
      },
      showTag() {
          this.$refs.LableList.load();
      },
      //传入一个对象，进行保存
      insert(obj,callback) {
          this.note = obj;
          this.save(() => {
              this.queryNoteById(this.note.nn_id)
              callback && callback();
          });
      },
      //紧急程度
      rightUrgency(val) {
          this.save();
      },

  },
  mounted(){}
 }
</script>

<style scoped>
</style>
